package com.hk.controlleradvice;

import com.hk.exception.BizException;
import com.hk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author: dpb
 * @Description 统一异常处理
 * @date: 2022/12/6 19:20
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice(basePackages = "com.hk.controller")
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R myException(Exception e) {
        if (e instanceof BizException) {
            BizException bizException = (BizException) e;
            return R.error(bizException.getMessageCode(), bizException.getMessage());
        } else if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            List<ObjectError> allErrors = validException.getBindingResult().getAllErrors();
            if (!allErrors.isEmpty()) {
                return R.error(allErrors.get(0).getDefaultMessage());
            } else {
                return R.error("MethodArgumentNotValidException");
            }
        } else {
            return R.error(e.getMessage());
        }
    }
}
